package com.jackchong.net

import com.blankj.utilcode.util.CacheDiskUtils
import kotlinx.coroutines.*
import java.io.Serializable
import java.lang.ClassCastException

/**
 * author : chong.huang
* create : 2/14/21
 * desc   :
 */
class CommonCache(private val strategy: CacheStrategy, private val hashCode: Int) : Cache {

    init {
        if (strategy.mode == CacheModeEnum.AUTO) {
            strategy.tag = NetCache.getUrl(hashCode)?: CacheStrategy.obtainTag()
        }
    }

    override fun read(block: (Serializable) -> Unit) {
        if (strategy.mode == CacheModeEnum.AUTO || strategy.mode == CacheModeEnum.TAG) {
            CoroutineScope(Dispatchers.IO).launch {
                val serializable = CacheDiskUtils.getInstance().getSerializable(strategy.tag!!)?: return@launch
                withContext(Dispatchers.Main){
                    block.invoke(serializable as Serializable)
                }
            }
        }
    }

    override fun write(any: Any?) {
        if (strategy.mode == CacheModeEnum.AUTO || strategy.mode == CacheModeEnum.TAG) {
            if (any == null) return
            if (!(any is Serializable)){
                throw ClassCastException("${any::class.java.name} 没有实现 Serializable 接口")
            }
            CoroutineScope(Dispatchers.IO).launch {
                CacheDiskUtils.getInstance().put(strategy.tag!!, any)
            }
        }
    }

    override fun cancel() {
        strategy.mode = CacheModeEnum.NOT
    }
}